from django.core.management.base import NoArgsCommand
from django.contrib.auth.models import User
from django.conf import settings
from invites.models import Invite
from datetime import datetime	

import sys

RESTORE_EXPIRED_INVITES = getattr(settings, 'INVITE_IN_TWO_STEPS', True)

#DeleteExpiredInvites Command named simply "dei". Maybe "die" would be better? =)
class Command(NoArgsCommand):
	
	def handle_noargs(self):

		try:
			if RESTORE_EXPIRED_INVITES:
				invites = Invite.objects.filter(expires__lte=datetime.now())
				senders = User.objects.filter(invites__in=invites)
				for invite in invites:
					invite.sender.invites_left+=1
				invites.delete()
				senders.save()
			else:
				Invite.objects.filter(expires__lte=datetime.now()).delete()
			print 'Expired ivites was succesfuly deleted.'
		except:
			print "Unexpected error:", sys.exc_info()[0]
			raise
